<template>
  <header class="course-title">
    <n-button class="btn-back" text @click="toList">
      <template #icon>
        <n-icon size="22"><ArrowBack /></n-icon>
      </template>
      <template #default>
        <span class="font-16"> 返回 </span>
      </template>
    </n-button>
    <button class="btn-style" @click="handleAddChapter">创建章节</button>
  </header>

  <div class="flex justify-between course-info align-center">
    <div class="flex justify-start">
      <img
        v-if="courseInfo.coverUrl"
        class="all_img page_style_one_img"
        :src="courseInfo.coverUrl"
        alt=""
      />
      <div v-else class="course-cover-container">
        <div class="default-image page_style_one_img" style="width: 228px; height: 122px">
          <img class="icon-none" src="~@/assets/icons/none.png" alt="" />
          <span>未上传封面</span>
        </div>
      </div>

      <div class="page_style_one_text">
        <div class="page_style_one_title"> {{ courseInfo.title || '课程名称加载失败' }} </div>
        <div class="page_style_one_content text_ellipsis_3">
          {{ courseInfo.description || '未填写课程描述' }}
        </div>
        <div class="page_style_one_date">
          {{ courseInfo.createTime ? formatToDate(new Date(courseInfo.createTime)) : '' }}
        </div>
      </div>
    </div>
    <n-dropdown trigger="hover" @select="courseSelect" :options="handleOptions">
      <n-button secondary class="btn-more">
        <template #icon>
          <n-icon size="22"><IosMore /></n-icon>
        </template>
      </n-button>
    </n-dropdown>
  </div>
  <n-divider />
  <div v-if="loading" class="loading">
    <div class="spinner"></div>
    <p>正在加载章节数据...</p>
  </div>
  <div v-else-if="dataList.length === 0" class="empty-state">
    <div class="empty-icon">
      <i class="fas fa-book-open"></i>
    </div>
    <h2 class="empty-title">暂无章节</h2>
    <p class="empty-desc">您还未添加任何章节</p>
  </div>
  <div v-else class="chapter-info">
    <n-grid cols="2 s:2 m:2 l:5 xl:5 2xl:5" responsive="screen" :x-gap="15">
      <n-grid-item v-for="(item, index) in dataList" :key="index" class="margin-bottom-30">
        <div class="box_shadow science">
          <div>
            <div class="chapter-container" @click="toDetail(item)">
              {{ `第${index + 1}章：${item.title}` }}
            </div>
            <div class="flex justify-between align-center margin-top-10">
              <div class="science_remark">{{
                item.createTime ? formatToDate(new Date(item.createTime)) : ''
              }}</div>
              <n-dropdown
                trigger="hover"
                @select="chapterSelect(item, $event)"
                :options="handleOptions"
              >
                <n-button secondary size="tiny" style="width: 40px">
                  <template #icon>
                    <n-icon size="18"><IosMore /></n-icon>
                  </template>
                </n-button>
              </n-dropdown>
            </div>
          </div>
        </div>
      </n-grid-item>
    </n-grid>
    <div class="flex justify-center">
      <n-pagination
        v-model:page="pageNum"
        :page-count="pages"
        size="large"
        :on-update:page="pageUpdate"
      />
    </div>
  </div>
  <course-write ref="courseWriteRef" :current-row="courseInfo" @finish="getCourseDetail" />
  <chapter-write
    ref="chapterWriteRef"
    :course-info="courseInfo"
    :current-row="chapterInfo"
    @finish="handleRefresh"
  />
</template>

<script lang="ts" setup>
  import { ref, unref, watch, nextTick } from 'vue';
  import { useDialog, useMessage } from 'naive-ui';
  import { ArrowBack } from '@vicons/ionicons5';
  import { IosMore } from '@vicons/ionicons4';
  import { useRouter } from 'vue-router';
  import { formatToDate } from '@/utils/dateUtil';
  import {
    getCourseDetailApi,
    deleteCourseApi,
    getChapterListApi,
    deleteChapterApi,
  } from '@/api/course';
  import CourseWrite from './components/CourseWrite.vue';
  import ChapterWrite from './components/ChapterWrite.vue';

  const router = useRouter();
  const dialog = useDialog();
  const message = useMessage();

  const props = defineProps({
    currentRow: {
      type: Object,
      default: () => null,
    },
  });

  /* 课程区域 */
  const emit = defineEmits(['back', 'next']);

  const handleOptions = [
    {
      label: '编辑',
      key: 0,
    },
    {
      label: '删除',
      key: 1,
    },
  ];

  //下拉菜单
  const courseSelect = (key: any) => {
    switch (key) {
      case 0:
        handleUpdateCourse();
        break;
      case 1:
        handleDeleteCourse();
        break;
    }
  };

  const courseWriteRef = ref();

  function handleUpdateCourse() {
    const write = unref(courseWriteRef);
    write.openModal();
  }

  async function handleDeleteCourse() {
    dialog.info({
      title: '提示',
      content: '确定删除吗？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        await deleteCourseApi(props.currentRow.courseId);
        message.success('课程已删除');
        toList();
      },
      onNegativeClick: () => {},
    });
  }

  const courseInfo = ref<any>({});

  async function getCourseDetail() {
    try {
      const data: any = await getCourseDetailApi(props.currentRow.courseId);
      courseInfo.value = data;
    } catch (e) {
      console.log('课程详情加载失败');
    }
  }

  watch(
    () => props.currentRow,
    async (currentRow) => {
      if (!currentRow) {
        message.error('课程信息加载失败，请稍后重试');
        return;
      }
      await nextTick();
      getCourseDetail();
      loadData();
    },
    {
      deep: true,
      immediate: true,
    }
  );

  /* 章节列表 */
  const pageNum = ref(1);
  const pageSize = 10;
  const loading = ref(false);
  const pages = ref(0);
  const dataList = ref<any[]>([]);

  async function loadData() {
    if (loading.value) return;
    loading.value = true;
    try {
      const params = {
        pageNum: pageNum.value,
        pageSize: pageSize,
        courseId: props.currentRow.courseId,
      };

      const data: any = await getChapterListApi(params);
      dataList.value = data.records || [];
      pages.value = data.pages;
    } catch (error) {
      console.error('error:', error);
    } finally {
      loading.value = false;
    }
  }

  function handleRefresh() {
    resetPage();
    loadData();
  }

  // 重置分页参数
  function resetPage() {
    pageNum.value = 1;
    dataList.value = [];
  }

  function pageUpdate(num: any) {
    pageNum.value = num;
    loadData();
  }

  /* 章节表单 */
  const chapterWriteRef = ref();
  const chapterInfo = ref<any>({});

  function handleAddChapter() {
    chapterInfo.value = null;
    const write = unref(chapterWriteRef);
    write.openModal();
  }

  function handleUpdateChapter(row: any) {
    chapterInfo.value = row;
    const write = unref(chapterWriteRef);
    write.openModal();
  }

  async function handleDeleteChapter(row: any) {
    dialog.info({
      title: '提示',
      content: '确定删除吗？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        await deleteChapterApi(row.chapterId);
        message.success('章节已删除');
        loadData();
      },
      onNegativeClick: () => {},
    });
  }

  //下拉菜单
  const chapterSelect = (row: any, key: any) => {
    switch (key) {
      case 0:
        handleUpdateChapter(row);
        break;
      case 1:
        handleDeleteChapter(row);
        break;
    }
  };

  function toList() {
    emit('back');
  }

  function toDetail(row: any) {
    emit('next', row);
    // router.push({ name: 'Video' });
  }
</script>
<style lang="less" scoped>
  .course-title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }

  .course-info {
    .btn-more {
      width: 60px;
    }
  }

  .chapter-container {
    background: linear-gradient(135deg, #6dc3ae 0%, #4ab69c 100%);
    color: white;
    height: 100px;
    line-height: 100px;
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    border-radius: 5px;
    padding: 0 5px;
  }

  .loading {
    text-align: center;
    padding: 40px;
    color: #7f8c8d;
  }

  .spinner {
    border: 4px solid rgba(0, 0, 0, 0.1);
    border-left-color: #4cb69b;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
    margin: 50px auto 20px;
  }

  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }

  .empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #7f8c8d;
  }

  .empty-icon {
    font-size: 80px;
    color: #ddd;
    margin-bottom: 20px;
  }

  .empty-title {
    font-size: 24px;
    margin-bottom: 15px;
    color: #95a5a6;
  }

  .empty-desc {
    font-size: 16px;
    max-width: 500px;
    margin: 0 auto 30px;
  }

  .chapter-info {
    .science_content {
      margin-top: 10px;
      line-height: 25px;
      font-size: 13px;
    }
    .science_remark {
      font-size: 12px;
      color: #6a6b6b;
    }
  }

  .img_cover {
    height: 105px;
  }
</style>
<style lang="less">
  .basicForm {
    padding-top: 20px;
  }

  .n-dialog.basicModal {
    width: 800px !important;
  }
</style>
